package net.wanho.shop.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import net.wanho.shop.common.MessageConstant;
import net.wanho.shop.common.OrderConstant;
import net.wanho.shop.dto.AddressDTO;
import net.wanho.shop.dto.OrderDTO;
import net.wanho.shop.mapper.OrderMapper;
import net.wanho.shop.po.Order;
import net.wanho.shop.service.OrderService;
import net.wanho.shop.vo.MessageVo;
import net.wanho.shop.vo.OrderDetailVO;
import net.wanho.shop.vo.OrderVo;
import net.wanho.shop.vo.PageVo;
import net.wanho.shop.webSocket.WebSocketServer;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.io.Serializable;
import java.util.List;


/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author 猛虎王
 * @since 2024-12-24
 */
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class OrderServiceImpl implements OrderService {

    private final OrderMapper orderMapper;
    private final RestTemplate restTemplate;
    private final WebSocketServer webSocketServer;

    /**
     * 订单表分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param order
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override

    public PageInfo findPage(int pageNum, int pageSize, Order order) {
        if (ObjectUtil.isNull(order)) {
            order = new Order();
        }

        // 分页
        PageHelper.startPage(pageNum, pageSize);
        List<Order> orderList = orderMapper.select(order);
        return new PageInfo(orderList);
    }

    /**
     * 根据主键查询订单表
     *
     * @param orderId
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public List<OrderDetailVO> findById(Integer orderId) {
        return orderMapper.selectById(orderId);
    }

    /**
     * 订单表新增
     *
     * @param order
     */
    @Override
    public void add(Order order) {
        orderMapper.insert(order);
    }

    /**
     * 修改订单表
     */
    @Override
    public void modify(Integer orderId, Integer status) {
        orderMapper.updateByOrderId(orderId, status);
    }

    /**
     * 根据主键删除订单表
     *
     * @param orderId
     */
    @Override
    public void removeById(Serializable orderId) {
        if (((String) orderId).contains(",")) {
            orderMapper.deleteByIds(((String) orderId).split(","));
        } else {
            orderMapper.deleteById(orderId);
        }
    }

    /**
     * 订单表分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param orderDTO
     * @return
     */
    @Override
    public PageVo findAll(int pageNum, int pageSize, OrderDTO orderDTO) {
        PageHelper.startPage(pageNum, pageSize);
        List<OrderVo> orderVos = orderMapper.selectAll(orderDTO);
        PageInfo<OrderVo> pageInfo = new PageInfo<>(orderVos);

        PageVo pageVo = new PageVo(pageInfo.getTotal(), pageNum);
        pageVo.put("orders", pageInfo.getList());

        return pageVo;
    }


    /**
     * 订单发货
     *
     * @param orderId
     * @param no
     */
    @Override
    public void send(Integer orderId, String no) {
        orderMapper.sendOrder(orderId, no);
    }

    /**
     * 修改地址
     *
     * @param orderId
     * @param address
     */
    @Override
    public void changeAddress(Integer orderId, AddressDTO address) {
        String consigneeAddr = address.getConsigneeAddr();
        orderMapper.updateAddressByOrderId(orderId, consigneeAddr);
    }

    /**
     * 查看物流信息
     *
     * @param no
     * @return
     */
    @Override
    public JSONArray findLogistics(String no) {
        String url = "https://wuliu.market.alicloudapi.com/kdi?no=" + no;
        String appcode = "e481169880834ae4bd7307a23f431ae7";

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "APPCODE " + appcode);
        HttpEntity<String> entity = new HttpEntity<>(headers);

        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        String body = response.getBody();
        JSONObject jsonObject = JSON.parseObject(body);
        assert jsonObject != null;
        JSONArray jsonArray = jsonObject.getJSONObject("result").getJSONArray("list");

        System.out.println(body);
        return jsonArray;
    }

    /**
     * 提醒发货
     *
     * @param orderId
     */
    @Override
    public void reminder(Integer orderId) {

        MessageVo messageVo = new MessageVo();
        messageVo.setType(MessageConstant.MESSAGE_TYPE_SEND);
        messageVo.setOrderId(orderId);

        Order order = orderMapper.selectByOrderId(orderId);
        messageVo.setOrderNumber(order.getOrderNumber());
        // 发送请求
        webSocketServer.sendToAllClient(JSON.toJSONString(messageVo));

    }

    @Async
    @Override
    public void updateOrderStatus(String orderNumber) {
        orderMapper.updateByOrderNumber(orderNumber, OrderConstant.COMPLETED);
        System.out.println("---------------------订单已支付，修改本地数据库");

    }


}
